/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cc.angis.xiugallery.image.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore.Images.Thumbnails;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import cc.angis.xiugallery.BuildConfig;
import cc.angis.xiugallery.R;
import cc.angis.xiugallery.SelectFavouriteActivity;
import cc.angis.xiugallery.SelectImageGridActivity;
import cc.angis.xiugallery.common.GlobalConst;
import cc.angis.xiugallery.image.util.ImageCache;
import cc.angis.xiugallery.image.util.ImageCache.ImageCacheParams;
import cc.angis.xiugallery.image.util.ImageResizer;
import cc.angis.xiugallery.image.util.ThumbnailImageLoader;
import cc.angis.xiugallery.image.util.Utils;
import cc.angis.xiugallery.provider.FavouriteImageProvider;
import cc.angis.xiugallery.provider.GalleryImageProvider;
import cc.angis.xiugallery.provider.ISourceProvider;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.slidingmenu.lib.app.SlidingFragmentActivity;

/**
 * The main fragment that powers the ImageGridActivity screen. Fairly straight forward GridView
 * implementation with the key addition being the ImageWorker class w/ImageCache to load children
 * asynchronously, keeping the UI nice and smooth and caching thumbnails for quick retrieval. The
 * cache is retained over configuration changes like orientation change so the images are populated
 * quickly as the user rotates the device.
 */
public class JBImageGridFragment extends SherlockFragment implements AdapterView.OnItemClickListener {
    private static final String TAG = "JBImageGridFragment";
    private static final String IMAGE_CACHE_DIR = "thumbs";

    protected int mImageThumbSize;
    protected int mImageThumbSpacing;
    protected ImageAdapter mAdapter;
    protected ImageResizer mImageWorker;
    protected ISourceProvider mProvider;
    
    private String id;
    
    private int type;
    
    private int menuType;
    
    /**
     * Factory method to generate a new instance of the fragment given an image number.
     *
     * @param imageNum The image number within the parent adapter to load
     * @return A new instance of ImageDetailFragment with imageNum extras
     */
    public static JBImageGridFragment newInstance(String id, int type, int menuType, String name) {
        final JBImageGridFragment f = new JBImageGridFragment();

        final Bundle args = new Bundle();
        args.putInt(GlobalConst.INTENT_GROUP_TYPE, type);
        args.putString(GlobalConst.INTENT_BUCKET_ID, id);
        args.putInt(GlobalConst.INTENT_MENU_TYPE, menuType);
        args.putString(GlobalConst.INTENT_BUCKET_NAME, name);
        f.setArguments(args);

        return f;
    }
    
    /**
     * Empty constructor as per the Fragment documentation
     */
    public JBImageGridFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        id = getArguments().getString(GlobalConst.INTENT_BUCKET_ID);
        type = getArguments().getInt(GlobalConst.INTENT_GROUP_TYPE);
        ActionBar actionbar = getSherlockActivity().getSupportActionBar();
        actionbar.setTitle(getArguments().getString(GlobalConst.INTENT_BUCKET_NAME));
        mImageThumbSize = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_size);
        mImageThumbSpacing = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_spacing);
        switch (type){
        	case 0:
        		mProvider = new GalleryImageProvider(getActivity(), id);
        		break;
        	case 1:
        		mProvider = new FavouriteImageProvider(getActivity(), id);
        	default:
        		mProvider = new FavouriteImageProvider(getActivity(), id);
        		break;
        }
        
        mAdapter = new ImageAdapter(getActivity());

        ImageCacheParams cacheParams = new ImageCacheParams(IMAGE_CACHE_DIR);

        // Allocate a third of the per-app memory limit to the bitmap memory cache. This value
        // should be chosen carefully based on a number of factors. Refer to the corresponding
        // Android Training class for more discussion:
        // http://developer.android.com/training/displaying-bitmaps/
        // In this case, we aren't using memory for much else other than this activity and the
        // ImageDetailActivity so a third lets us keep all our sample image thumbnails in memory
        // at once.
        cacheParams.memCacheSize = 1024 * 1024 * Utils.getMemoryClass(getActivity()) / 3;

        // The ImageWorker takes care of loading images into our ImageView children asynchronously
        mImageWorker = new ThumbnailImageLoader(getActivity(), mImageThumbSize, Thumbnails.MICRO_KIND);
        mImageWorker.setAdapter(mProvider);
        mImageWorker.setLoadingImage(R.drawable.empty_photo);
        mImageWorker.setImageCache(ImageCache.findOrCreateCache(getActivity(), cacheParams));
    }

    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        final View v = inflater.inflate(R.layout.image_grid_fragment, container, false);
        final GridView mGridView = (GridView) v.findViewById(R.id.gridView);
        mGridView.setAdapter(mAdapter);
        mGridView.setOnItemClickListener(this);

        // This listener is used to get the final width of the GridView and then calculate the
        // number of columns and the width of each column. The width of each column is variable
        // as the GridView has stretchMode=columnWidth. The column width is used to set the height
        // of each view so we get nice square thumbnails.
        mGridView.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        if (mAdapter.getNumColumns() == 0) {
                            final int numColumns = (int) Math.floor(
                                    mGridView.getWidth() / (mImageThumbSize + mImageThumbSpacing));
                            if (numColumns > 0) {
                                final int columnWidth =
                                        (mGridView.getWidth() / numColumns) - mImageThumbSpacing;
                                mAdapter.setNumColumns(numColumns);
                                mAdapter.setItemHeight(columnWidth);
                                if (BuildConfig.DEBUG) {
                                    Log.d(TAG, "onCreateView - numColumns set to " + numColumns);
                                }
                            }
                        }
                    }
                });

        return v;
    }

    @Override
    public void onResume() {
        super.onResume();
        mImageWorker.setExitTasksEarly(false);
        mProvider.initSource();
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onPause() {
        super.onPause();
        mImageWorker.setExitTasksEarly(true);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        final Intent i = new Intent(getActivity(), ImageDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt(GlobalConst.INTENT_CUR_IMAGE_SEQUENCE, position);
        bundle.putString(GlobalConst.INTENT_BUCKET_ID, this.id);
        bundle.putInt(GlobalConst.INTENT_GROUP_TYPE, type);
        i.putExtras(bundle);
        startActivity(i);
    }
    
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//		if (type == 1)
		menuType = getArguments().getInt(GlobalConst.INTENT_MENU_TYPE);
		switch (menuType){
			case GlobalConst.MenuType.MENU_TYPE_ADDIMAGE:
				inflater.inflate(R.menu.menu2, menu);
				break;
//			case GlobalConst.MenuType.MENU_TYPE_IMAGEDISPLAY:
//				inflater.inflate(R.menu.menu2, menu);
//				break;
			default:
				break;
		}
		super.onCreateOptionsMenu(menu, inflater);
	}
	
	@Override
	public boolean onOptionsItemSelected(
			com.actionbarsherlock.view.MenuItem item) {
		switch(item.getItemId()){
			case android.R.id.home:
				if (getActivity() instanceof SlidingFragmentActivity){
					((SlidingFragmentActivity)getActivity()).getSlidingMenu().showBehind();
				} else
					getActivity().finish();
				break;
			case R.id.add_img_fav_button:
//				final Intent i = new Intent(getActivity(), SelectFavouriteActivity.class);
//				i.putExtra(GlobalConst.INTENT_FAVOURITE_ID, id);
//		        startActivity(i);
				final Intent i = new Intent(getActivity(), SelectImageGridActivity.class);
		        i.putExtra(GlobalConst.INTENT_BUCKET_ID,  GlobalConst.CAMERA_IMAGE_BUCKET_ID);
		        i.putExtra(GlobalConst.INTENT_FAVOURITE_ID, id);
		        startActivity(i);
				break;
			default:
				break;
		}
		return super.onOptionsItemSelected(item);
	}


    /**
     * The main adapter that backs the GridView. This is fairly standard except the number of
     * columns in the GridView is used to create a fake top row of empty views as we use a
     * transparent ActionBar and don't want the real top row of images to start off covered by it.
     */
    private class ImageAdapter extends BaseAdapter {

        private final Context mContext;
        private int mItemHeight = 0;
        private int mNumColumns = 0;
        private GridView.LayoutParams mImageViewLayoutParams;

        public ImageAdapter(Context context) {
            super();
            mContext = context;
            mImageViewLayoutParams = new GridView.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        }

        @Override
        public int getCount() {
            // Size of adapter + number of columns for top empty row
            return mImageWorker.getAdapter().getSize();
        }

        @Override
        public Object getItem(int position) {
        	return mImageWorker.getAdapter().getImageItem(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getViewTypeCount() {
            // Two types of views, the normal ImageView and the top row of empty views
            return 1;
        }

        @Override
        public int getItemViewType(int position) {
        	 return 0;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup container) {
            // Now handle the main ImageView thumbnails
            ImageView imageView;
            if (convertView == null) { // if it's not recycled, instantiate and initialize
                imageView = new ImageView(mContext);
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setLayoutParams(mImageViewLayoutParams);
            } else { // Otherwise re-use the converted view
                imageView = (ImageView) convertView;
            }

            // Check the height matches our calculated column width
            if (imageView.getLayoutParams().height != mItemHeight) {
                imageView.setLayoutParams(mImageViewLayoutParams);
            }

            // Finally load the image asynchronously into the ImageView, this also takes care of
            // setting a placeholder image while the background thread runs
            mImageWorker.loadImage(position, imageView);
            return imageView;
        }

        /**
         * Sets the item height. Useful for when we know the column width so the height can be set
         * to match.
         *
         * @param height
         */
        public void setItemHeight(int height) {
            if (height == mItemHeight) {
                return;
            }
            mItemHeight = height;
            mImageViewLayoutParams =
                    new GridView.LayoutParams(LayoutParams.MATCH_PARENT, mItemHeight);
            mImageWorker.setImageSize(height);
            notifyDataSetChanged();
        }

        public void setNumColumns(int numColumns) {
            mNumColumns = numColumns;
        }

        public int getNumColumns() {
            return mNumColumns;
        }
    }

	@Override
	public void onDestroyView() {
		final ImageCache cache = mImageWorker.getImageCache();
        if (cache != null) {
            mImageWorker.getImageCache().clearCaches();
//            DiskLruCache.clearCache(getActivity(), ImageFetcher.HTTP_CACHE_DIR);
//            Toast.makeText(getActivity(), R.string.clear_cache_complete,
//                    Toast.LENGTH_SHORT).show();
        }
		super.onDestroyView();
	}
}
